package client;

import java.io.IOException;
import java.util.ArrayList;



import common.Log;
import common.Logger;
import communication.Message;
import communication.client.ServerHandle;
import communication.message.*;
import exception.ParseException;

public class Main {

	private static Logger logger = Log.getInstance(Main.class);

	private static void usage() {
		System.err.println("usage: ./player --connect_to IP:PORT --nick NICK");
	}

	// --connect_to 127.0.0.1:1500 --nick pentanodion
	public static void main(String[] args) {

		try {

			if (args.length != 4 || !args[0].equalsIgnoreCase("--connect_to")
					|| !args[2].equals("--nick")) {
				usage();
				System.exit(-1);
			}

			String[] addr = args[1].split(":");
			String ip = addr[0];

			int port = Integer.parseInt(addr[1]);
			String nick = args[3];

			logger.info("Client: " + nick + " started...");

			ServerHandle s = new ServerHandle(ip, port);
			s.connect(new PlayerLogin(nick, "paper_football"));

			logger.info("Connected to server: " + ip + ":" + port);

			Message msg = s.receiveMessage();
			if (msg.getType().toString().equalsIgnoreCase("loginresponse")) {
				if (msg.getResponse().getAccept())
					System.err.println("Login SUCCESS!");
				else
					System.err.println("Login FAILED!");
			}
			while (true) {
				GameLoop(s, nick);
			}

		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		}

	}

	private static void GameLoop(ServerHandle s, String nick)
			throws ParseException, IOException {
		Message msg;
		PaperSoccerAI ai = new PaperSoccerAI(nick);

		while (true) {
			msg = s.receiveMessage();

			
			if (msg.getType().toString().equalsIgnoreCase("gamestate")) {
				if (msg.getGameOver() != null)
					break;
				
				
					msg = ai.GetAIResponse(msg);
					if (msg != null) {
						
						s.sendMove(msg.getGameId(), msg.getMove());
					}
				
			} else {
				
			}
		}
		s.finishGame(msg.getGameId());
		annouceResults(msg.getGameOver().getPlayers(), nick);
	}

	private static void annouceResults(ArrayList<Player> players, String myNick) {
		String winner = "";
		for (Player p : players) {
			if (p.getResult() == Result.WINNER)
				winner = p.getNick();
			if (p.getNick().equals(myNick))
				logger.info(p.getResult() == Result.WINNER ? "wygrana"
						: "przegrana");
		}
		if (!winner.equals(myNick))
			logger.info("Wygrał " + winner + ". ");
	}

}
